package jwt

import (
	"gin-demo/pkg/util"
	"github.com/gin-gonic/gin"
	"log"
)

// jwt中间件

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		response := util.NewResponseSuccess()
		// 获取token
		token := c.Query("token")
		// 打印日志
		log.Println("token_1:", token)
		// logging.Info("token_1:", token)
		if token == "" {
			// 从header获取token
			authorization := c.GetHeader("Authorization")
			// 打印日志
			log.Println("authorization:", authorization)
			if authorization == "" || len(authorization) <= 7 {
				response.Code = 422
				response.Msg = "token不能为空"
				util.ResponseSuccess(c, response)
				c.Abort()
				return
			}
			token = authorization[7:] // Bearer 空格
			// 打印日志
			log.Println("token_2:", token)
		}
		if token == "" {
			response.Code = 422
			response.Msg = "token不能为空"
			util.ResponseSuccess(c, response)
			c.Abort()
			return
		}
		// 解析token
		parseToken, err := util.ParseToken(token)
		if err != nil || parseToken.ID == 0 {
			response.Code = 422
			response.Msg = "token认证失败"
			util.ResponseUnAuth(c, response)
			c.Abort()
			return
		}

		// 认证成功
		c.Next()
	}
}
